import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_exam_test_count.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine_uestion.dart';
import 'package:flutter_learn_vi/src/bean/bean_problem.dart';
import 'package:flutter_learn_vi/src/bean/bean_problem_end.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/topic/data/count_model.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_item_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_drawer_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_end_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import '../../bean/bean_ExamBean.dart';
import '../../bean/bean_problem_rule.dart';
import '../../face/face_detector_view.dart';
import '../../utils/log_util.dart';
import 'controller/question_error_controller.dart';
import 'data/topic_text_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/12.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///答题主页面
class TopicDetilsPage extends StatefulWidget {
  final String pageTitle;
  final String themTitle;

  //培训考试
  final String examUid;

  //培训考试
  final BeanExamBean examBean;
  final String categoryOne;
  final String categoryTwo;
  final List<ProblemModel> problemList;

  ///考试类型 机考使用
  final String examType;

  ///学习任务ID
  final int taskId;

  ///答题类型
  final TopicEnum topicEnum;

  TopicDetilsPage(
      {this.pageTitle,
      @required this.categoryOne,
      @required this.categoryTwo,
      this.topicEnum = TopicEnum.common,
      this.taskId,
      this.themTitle,
      this.examBean,
      this.examUid,
      this.examType,
      this.problemList});

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TopicDetilsPage>
    with WidgetsBindingObserver {
  bool isLevel = false;
  bool _isFinish = false;
  bool isCheckError = false;

  @override
  void initState() {
    super.initState();
    // 必须添加观察者监听
    WidgetsBinding.instance?.addObserver(this);
    Get.put(AuestionErrorController());
    ExamTestCountConfigBean examTestCountConfigBean =
        UserHelper.getInstance.examTestCountConfigBean;
    if (examTestCountConfigBean != null) {
      if (examTestCountConfigBean.examTimeCount != 0) {
        totalTime = examTestCountConfigBean.examTimeCount * 60;
      }
    }
    if (widget.topicEnum != TopicEnum.error) {
      Future.delayed(Duration.zero, () {
        context.read<TopicTextModel>().init();
        context.read<CountModel>().init();
      });
    }
    initRequest();
  }

  void initRequest() async {
    if (widget.examBean != null) {
      //考试时间
      int examTim = widget.examBean.examTim;
      if (examTim == null) {
        dynamic result = await _getExamDetails();
        if (result != null) {
          if (!result) {
            return;
          }
        }
      } else {
        totalTime = examTim * 60;
      }
    }

    switch (widget.topicEnum) {
      case TopicEnum.common:
        await _getExaminConfig();
        //普通抽题
        await _getCommonQuestion();
        break;
      case TopicEnum.muyCollect:
        await _getExaminConfig();
        //普通抽题 我的收藏
        _getCommonQuestion();
        break;
      case TopicEnum.pcExam:
        await _getExaminConfig();
        //新建考试抽题
        _getNewExamQuestion();
        break;
      case TopicEnum.train:
        await _getExaminConfig();
        //培训抽题
        _getExamQuestionList();
        break;
      case TopicEnum.error:
        //查看错题
        context.read<CountModel>().initList(widget.problemList);
        _isFinish = true;
        isCheckError = true;
        break;
      case TopicEnum.pcTest:
        await _getExaminConfig();
        // PC考试
        _getpCExampQuestion();
        break;
      case TopicEnum.myError:
        // 我的错题
        _getCommonQuestion();
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        bool isCheck = true;
        if (widget.topicEnum == TopicEnum.myError ||
            widget.topicEnum == TopicEnum.error ||
            widget.topicEnum == TopicEnum.muyCollect) {
          return true;
        }
        if (!isCheckError &&
            (context.read<CountModel>().problemList.length) > 0) {
          isCheck = await submitAn();
        }
        return isCheck;
      },
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: widget.pageTitle == null
            ? null
            : AppBar(
                leading: BackButton(
                  onPressed: () async {
                    bool isCheck = true;
                    if (widget.topicEnum == TopicEnum.myError ||
                        widget.topicEnum == TopicEnum.error ||
                        widget.topicEnum == TopicEnum.muyCollect) {
                      Navigator.of(context).pop();
                      return true;
                    }
                    if (!isCheckError &&
                        (context.read<CountModel>().problemList.length) > 0) {
                      isCheck = await submitAn();
                    }
                  },
                ),
                title: Text("${widget.pageTitle}"),
                actions: [
                  GetBuilder(
                    builder: (AuestionErrorController controller) {
                      List<ProblemModel> requestList = controller.requestList;
                      if (requestList.length == 0) {
                        return SizedBox(
                          child: Text("无"),
                        );
                      }
                      return Builder(builder: (BuildContext context) {
                        return TextButton(
                            onPressed: () {
                              Scaffold.of(context).openEndDrawer();
                            },
                            child: Text("目录"));
                      });
                    },
                  )
                ],
              ),
        endDrawer: GetBuilder(
          builder: (AuestionErrorController controller) {
            return buildEndDrawer();
          },
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: buildBody(),
        ),
        floatingActionButton: buildSubmitWidget(),
      ),
    );
  }

  buildEndDrawer() {
    return TopicDrawerPage();
  }

  String _errorText = "暂无题型，请等待管理员上传该分类下题库";

  Future<bool> _getNewExamQuestion() async {
    if (widget.examBean == null ||
        widget.examBean.examUid == null ||
        widget.examBean.examUid.isEmpty) {
      Get.defaultDialog(
          title: "提示",
          content: Text("暂无法获取考试详情"),
          textCancel: "退出",
          onCancel: () {
            Get.back();
          });
      return false;
    }
    _isFinish = false;
    Map<String, dynamic> jsonMap = Map();
    jsonMap["examUid"] = widget.examBean.examUid;
    if (widget.examType != null) {
      jsonMap["examType"] = widget.examType;
    }
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.questionPcExpamw + "/${widget.examBean.examUid}",
      jsonMap: jsonMap,
    );
    _isFinish = true;
    List<ProblemModel> requestList = [];
    if (responseInfo.success) {
      List list = responseInfo.data;
      list.forEach((element) {
        ProblemModel problemModel = ProblemModel.fromJson(element);
        requestList.add(problemModel);
      });
    } else {
      ToastUtils.showToast("${responseInfo.message}");
      setState(() {
        _errorText = responseInfo.message;
      });
      return false;
    }
    if (requestList.length > 0) {
      _pageStreamController.add("1/${requestList.length}");
      startTimer();
    }
    if (Get.isRegistered<AuestionErrorController>()) {
      Get.find<AuestionErrorController>().onTopicList(requestList);
    }
    context.read<CountModel>().initList(requestList);
    setState(() {});
    return Future.value(true);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        LogUtils.e("页面状态前台${state} $currentSwitchNumber");
        if (_examinNewConfigItemEntity != null) {
          if (currentSwitchNumber > switchScreenNumber) {
            LogUtils.e("切屏资料上限 自动交卷");
            Get.defaultDialog(
              title: "提示",
              barrierDismissible: false,
              content: Text("已达切屏限制${switchScreenNumber}次,将会自动交卷"),
            );
            Future.delayed(Duration(seconds: 2), () {
              Get.back();
              _timer.cancel();
              if (widget.topicEnum == TopicEnum.pcTest) {
                //机考提交
                pcExampleFinishCommitFunction();
              } else {
                commonFinishCommitFunction();
              }
            });
          } else {
            Get.defaultDialog(
                title: "提示",
                content: Text(
                    "当前还有${switchScreenNumber - currentSwitchNumber}次切屏机会"),
                textCancel: "知道了");
          }
        }

        break;
      case AppLifecycleState.paused:
        currentSwitchNumber++;
        LogUtils.e("页面状态后台${state} $currentSwitchNumber");
        break;
      case AppLifecycleState.inactive:
        LogUtils.e("页面 inactive ${state}");
        break;
      case AppLifecycleState.detached:
        LogUtils.e("页面状态 detached ${state}");
        break;
    }
  }

  ProblemRuleModel _problemRuleModel;
  ExaminNewConfigItemEntity _examinNewConfigItemEntity;
  int switchScreenNumber = 1000;
  int currentSwitchNumber = 0;

  ///获取答题的配置
  Future<bool> _getExaminConfig() async {
    ResponseInfo responseRuleInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.examinConfigUrl,
    );
    if (responseRuleInfo.success) {
      if (responseRuleInfo.data != null) {
        _examinNewConfigItemEntity =
            ExaminNewConfigItemEntity.fromJson(responseRuleInfo.data);
        switchScreenNumber = _examinNewConfigItemEntity.switchScreenNumber;
        Get.defaultDialog(
            title: "提示",
            content: Text("${_examinNewConfigItemEntity.switchScreenMessage}"),
            textCancel: "知道了");
      } else {
        LogUtils.e("请求完成 当前无答题配置");
      }
    } else {
      LogUtils.e("请求错误 当前无答题配置");
    }
    return true;
  }

  //获取练习题
  Future<bool> _getCommonQuestion() async {
    MineQuestionBean mineQuestionBean =
        UserHelper.getInstance.selectMineQuestionBean;

    if (mineQuestionBean == null) {
      ToastUtils.showToast("请选择题库");
      return false;
    }
    Map<String, dynamic> map = Map();
    map["categoryOne"] = widget.categoryOne;
    map["questionUid"] = mineQuestionBean.questionUid;
    map["categoryTwo"] = widget.categoryTwo;

    _isFinish = false;

    String url = HttpHelper.questionV2;

    ///我的错题
    if (widget.topicEnum == TopicEnum.myError) {
      url = HttpHelper.questionwrongUrl;
    } else if (widget.topicEnum == TopicEnum.muyCollect) {
      url = HttpHelper.questionMyCollectUrl;
    }
    //获取抽题规则
    String ruleurl = HttpHelper.questionRule;
    ResponseInfo responseRuleInfo = await DioUtils.instance.getRequest(
      url: ruleurl,
      queryParameters: map,
    );
    if (responseRuleInfo.success) {
      if (responseRuleInfo.data == null) {
        ToastUtils.showToast("未设置抽题规则");
        Get.defaultDialog(
          title: "提示",
          content: Text("未设置抽题规则"),
          textCancel: "知道了",
        );
        _isFinish = true;
        setState(() {});
        return false;
      }
      _problemRuleModel = ProblemRuleModel.fromJson(responseRuleInfo.data);
      totalTime = _problemRuleModel.randomTime;
    }

    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: url,
      queryParameters: map,
    );

    _isFinish = true;
    List<ProblemModel> requestList = [];
    if (responseInfo.success) {
      List list = responseInfo.data;
      list.forEach((element) {
        ProblemModel problemModel = ProblemModel.fromJson(element);
        requestList.add(problemModel);
      });
    } else {
      ToastUtils.showToast("${responseInfo.message}");
      setState(() {
        _errorText = responseInfo.message;
      });
      return false;
    }
    if (requestList.length > 0) {
      _pageStreamController.add("1/${requestList.length}");
      //我的错题不需要计时
      if (widget.topicEnum != TopicEnum.myError) {
        startTimer();
      } else {}
    }
    if (Get.isRegistered<AuestionErrorController>()) {
      Get.find<AuestionErrorController>().onTopicList(requestList);
    }
    context.read<CountModel>().initList(requestList);
    setState(() {});
    return Future.value(true);
  }

  //机考题
  Future<bool> _getpCExampQuestion() async {
    Map<String, dynamic> map = Map();
    map["categoryOne"] = widget.categoryOne;
    map["categoryTwo"] = widget.categoryTwo;
    map["examType"] = widget.examType;
    _isFinish = false;
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.questionPcExpam,
      jsonMap: map,
    );
    _isFinish = true;
    List<ProblemModel> requestList = [];
    if (responseInfo.success) {
      List list = responseInfo.data;
      list.forEach((element) {
        ProblemModel problemModel = ProblemModel.fromJson(element);
        requestList.add(problemModel);
      });
    } else {
      ToastUtils.showToast("${responseInfo.message}");
      setState(() {
        _errorText = responseInfo.message;
      });
      return false;
    }
    if (requestList.length > 0) {
      if (Get.isRegistered<AuestionErrorController>()) {
        Get.find<AuestionErrorController>().onTopicList(requestList);
      }
      _pageStreamController.add("1/${requestList.length}");
      startTimer();
    }
    context.read<CountModel>().initList(requestList);
    setState(() {});
    return Future.value(true);
  }

  Future<bool> _getExamQuestionList() async {
    if (widget.examBean == null ||
        widget.examBean.examUid == null ||
        widget.examBean.examUid.isEmpty) {
      Get.defaultDialog(
          title: "提示",
          content: Text("暂无法获取考试详情"),
          textCancel: "退出",
          onCancel: () {
            Get.back();
          });
      return false;
    }
    Map<String, dynamic> map = new Map();
    map['examUid'] = widget.examBean.examUid;
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.examQuestionByExamUid,
      jsonMap: map,
    );
    _isFinish = true;
    List<ProblemModel> requestList = [];
    if (responseInfo.success) {
      List list = responseInfo.data;
      list.forEach((element) {
        ProblemModel problemModel = ProblemModel.fromJson(element);
        requestList.add(problemModel);
      });
    } else {
      ToastUtils.showToast("${responseInfo.message}");
      setState(() {
        _errorText = responseInfo.message;
      });
      return false;
    }
    if (requestList.length > 0) {
      if (Get.isRegistered<AuestionErrorController>()) {
        Get.find<AuestionErrorController>().onTopicList(requestList);
      }
      _pageStreamController.add("1/${requestList.length}");
      startTimer();
    }
    context.read<CountModel>().initList(requestList);
    setState(() {});
    return Future.value(true);
  }

  buildBody() {
    if (!_isFinish) {
      return Center(child: LoadingWidget());
    }
    if (context.watch<CountModel>().problemList.length == 0) {
      return Center(
          child: NoDataWidget(
        text: _errorText,
        clickCallBack: () {
          _isFinish = false;
          setState(() {});
          Future.delayed(Duration(milliseconds: 400), () {
            initRequest();
          });
        },
      ));
    }
    return Stack(
      children: [
        Positioned.fill(
          child: buildPageView(),
        ),
        buildPositioned(),
        Positioned(
          child: buildBottomContainer(),
          bottom: 15,
          left: 20,
        ),
      ],
    );
  }

  Widget buildPositioned() {
    if (isCheckError) {
      return Container();
    }
    return Positioned(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(33))),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.menu_book_sharp,
                    color: Colors.redAccent,
                    size: 14,
                  ),
                  SizedBox(
                    width: 2,
                  ),
                  StreamBuilder(
                    stream: _pageStreamController.stream,
                    initialData: context.watch<CountModel>().problemList != null
                        ? "1/${context.watch<CountModel>().problemList.length}"
                        : "0/0",
                    builder:
                        (BuildContext context, AsyncSnapshot<String> snapshot) {
                      return Text("${snapshot.data}");
                    },
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: GetBuilder(
              id: "collectFunction",
              builder: (AuestionErrorController controller) {
                bool currentIsCollection = controller.getCurrentIsCollection();
                return TextButton(
                  child: Text(currentIsCollection ? "已收藏" : "收藏"),
                  onPressed: () {
                    Get.find<AuestionErrorController>().collectFunction();
                    // double currentPage = _pageController.nextPage();
                  },
                );
              },
            ),
          ),
          Expanded(
            child: TextButton(
              child: Text("上一题"),
              onPressed: () {
                Get.find<AuestionErrorController>().previousPage();
                // double currentPage = _pageController.nextPage();
              },
            ),
          ),
          Expanded(
            child: TextButton(
              child: Text("下一题"),
              onPressed: () {
                Get.find<AuestionErrorController>().nextPage();
                // double currentPage = _pageController.nextPage();
              },
            ),
          ),
        ],
      ),
      bottom: 100,
      right: 20,
      left: 20,
    );
  }

  Widget buildBottomContainer() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            buildTimeWidget(),
          ],
        ),
        SizedBox(
          height: 12,
        ),
        Container(
          margin: EdgeInsets.only(bottom: 10, right: 10),
          child: buildLeftTime(),
        )
      ],
    );
  }

  buildTimeWidget() {
    if (isCheckError) {
      return Container();
    }
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.lock_clock,
          color: Colors.blueGrey,
          size: 16,
        ),
        SizedBox(
          width: 4,
        ),
        StreamBuilder(
          stream: _timeController.stream,
          initialData: "00:00",
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            return SizedBox(
              width: 60,
              child: Text("${snapshot.data}"),
            );
          },
        ),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 4,
            ),
            Consumer<CountModel>(builder: (
              BuildContext context,
              CountModel contModel,
              Widget child,
            ) {
              return Text(
                "未答${contModel.noAnwesrCont}题",
                style: TextStyle(color: Colors.red),
              );
            }),
          ],
        )
      ],
    );
  }

  StreamController<String> _timeController = new StreamController();
  StreamController<String> _pageStreamController = new StreamController();

  //答题正确是否

  Consumer buildPageView() {
    return Consumer<CountModel>(
        builder: (BuildContext context, CountModel model, Widget child) {
      return PageView.builder(
        controller: Get.find<AuestionErrorController>().pageController,
        itemCount: model.problemList.length,
        onPageChanged: (value) {
          _pageStreamController.add("${value + 1}/${model.problemList.length}");
        },
        itemBuilder: (BuildContext context, int index) {
          ProblemModel problemModel = model.problemList[index];
          return TopicDetailsItemPage(
            isCheckError: isCheckError,
            problemModel: problemModel,
            key: ValueKey("$index"),
            topicEnum: widget.topicEnum,
          );
        },
      );
    });
  }

  Timer _timer;
  int totalTime = 60 * 60;
  int currentTime = 0;
  int faceRecognitionNumber = 0;

  //正在显示的人脸识别的提示
  bool showFaceTips = false;

  void startTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (currentTime >= totalTime) {
        submitCheckFunction(isFinsh: false);
        _timer.cancel();
        return;
      }
      faceRecognitionNumber += 1;
      currentTime += 1;
      int flag = totalTime - currentTime;
      int min = flag ~/ 60;
      int sen = flag % 60;
      String minStr = "$min";
      if (min < 10) {
        minStr = "0$min";
      }
      String senStr = "$sen";
      if (sen < 10) {
        senStr = "0$sen";
      }
      if (mounted) {
        bool isShowFaceCheck = UserHelper.getInstance.isShowFaceCheck();
        if (isShowFaceCheck) {
          if (!showFaceTips) {
            checkFaceFunction();
          }
        } else {
          debugPrint("人脸识别权限关闭");
        }
      }
      _timeController.add("${minStr}:${senStr}");
    });
  }

  Future<bool> checkFaceFunction() async {
    if (widget.examBean == null) {
      return false;
    }
    String faceRecognition = widget.examBean.faceRecognition;
    if (faceRecognition != "on") {
      return false;
    }

    //自动识别的间隔时间 分钟
    int faceRecognitionTime = widget.examBean.faceRecognitionTime;
    //分钟转秒
    int faceRecognitionTimeSeconds = faceRecognitionTime * 60;
    //测试使用
    // faceRecognitionTimeSeconds = 10;
    //如果本地时间大于人脸识别时间
    debugPrint(
      "人脸识别时间 faceRecognitionTimeSeconds：$faceRecognitionTimeSeconds  faceRecognitionNumber：${faceRecognitionNumber}",
    );

    if (faceRecognitionNumber > faceRecognitionTimeSeconds) {
      debugPrint("需要开启人脸识别 ");
      showFaceTips = true;
      dynamic result = await Get.defaultDialog(
          title: "提示",
          content: Text("本考试需要人脸识别认证，认证通过后可继续考试"),
          textCancel: "取消",
          textConfirm: "去认证",
          radius: 10,
          onConfirm: () {
            Get.back(result: true);
          });
      if (result == null || !result) {
        debugPrint("未选择去认证");
        ToastUtils.showToast("需要认证后才能继续考试 否则将无法继续考试");
        dynamic r = await submitAn();
        if (r == null || !r) {
          showFaceTips = false;
        }
        return false;
      }

      dynamic faceResult = await Get.to(() => FaceDetectorView(
            key: UniqueKey(),
          ));
      if (faceResult == null || faceResult.toString().isEmpty) {
        ToastUtils.showToast("需要认证后才能继续考试 否则将无法继续考试");
        dynamic r = await submitAn();
        if (r == null || !r) {
          showFaceTips = false;
        }
        return false;
      }
      //比对一下当前的人脸数据
      ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
          url: HttpHelper.compareFaceUrl,
          encrypt: false,
          jsonMap: {
            "examUid": widget.examUid,
            "faceType": "exam",
            "faceImageUrl": faceResult.toString(),
          });

      if (statisRresponseInfo.success) {
        //识别成功 继续播放
        debugPrint("人脸识别成功 继续播放");
        faceRecognitionNumber = 0;
        showFaceTips = false;
      } else {
        dynamic result = await Get.defaultDialog(
            radius: 10,
            title: "人脸信息核定失败",
            content: Text(statisRresponseInfo.message ?? "网络请求错误"),
            textCancel: "关闭");
        dynamic r = await submitAn();
        if (r == null || !r) {
          showFaceTips = false;
        }
        return true;
      }
      return false;
    }
  }

  void submitCheckFunction({bool isFinsh = true}) {
    showCupertinoDialog(
        barrierDismissible: false,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("提示"),
            content: Container(
              padding: EdgeInsets.all(16),
              child: Text("考试时间到 正在交卷中！！！"),
            ),
          );
        },
        context: context);
    _timer.cancel();
    if (widget.topicEnum == TopicEnum.pcTest) {
      //机考提交
      pcExampleFinishCommitFunction();
    } else {
      commonFinishCommitFunction();
    }
  }

  Future<bool> submitAn() async {
    bool flag = await showCupertinoDialog(
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("提示"),
            content: Container(
              padding: EdgeInsets.all(16),
              child: Text("确定要交卷吗！！！"),
            ),
            actions: [
              CupertinoDialogAction(
                child: Text("再检查一下"),
                onPressed: () {
                  NavigatorUtils.pop(context, parameters: false);
                },
              ),
              CupertinoDialogAction(
                child: Text("检查好了"),
                onPressed: () {
                  NavigatorUtils.pop(context, parameters: true);
                },
              ),
            ],
          );
        },
        context: context);

    if (!flag) {
      return false;
    }

    _timer.cancel();

    if (widget.topicEnum == TopicEnum.pcTest) {
      //机考提交
      pcExampleFinishCommitFunction();
    } else {
      commonFinishCommitFunction();
    }
    return true;
  }

  ///机考方式交卷
  Future pcExampleFinishCommitFunction() async {
    Map<String, dynamic> map = Map();
    map["categoryOne"] = widget.categoryOne;
    map["categoryTwo"] = widget.categoryTwo;
    map["answerTime"] = currentTime;
    map["questionAnswers"] = context.read<CountModel>().commitList;

    _isFinish = false;
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance
        .postRequest(url: HttpHelper.questionPcExpamSubmit, jsonMap: map);
    if (responseInfo.success) {
      ProblemEndModel problemEndModel =
          ProblemEndModel.fromJson(responseInfo.data);

      NavigatorUtils.openPageByFade(
          context,
          TopicEndPage(
            problemEndModel: problemEndModel,
            pageTitle: widget.themTitle,
            topicEnum: widget.topicEnum,
            categoryOne: widget.categoryOne,
            categoryTwo: widget.categoryTwo,
          ),
          opaque: false,
          isReplace: true);
    } else {
      ToastUtils.showToast("交卷失败 ${responseInfo.message}");
    }
  }

  //普通交卷方式
  Future commonFinishCommitFunction() async {
    Map<String, dynamic> map = Map();
    map["categoryOne"] = widget.categoryOne;
    map["categoryTwo"] = widget.categoryTwo;
    if (widget.topicEnum == TopicEnum.train) {
      map["examEumu"] = "train";
      if (widget.examBean != null &&
          widget.examBean.examUid != null &&
          widget.examBean.examUid.isNotEmpty) {
        map["examUid"] = widget.examBean.examUid;
      }
      map["examType"] = widget.examType;
    } else if (widget.topicEnum == TopicEnum.pcExam) {
      map["examEumu"] = "pcExam";
      if (widget.examBean != null &&
          widget.examBean.examUid != null &&
          widget.examBean.examUid.isNotEmpty) {
        map["examUid"] = widget.examBean.examUid;
      }
      map["examType"] = widget.examType;
    } else if (widget.topicEnum == TopicEnum.muyCollect) {
      map["examEumu"] = "muyCollect";
      map["examType"] = widget.examType;
    } else {
      map["examEumu"] = "common";
    }

    ///学习任务ID 提交答案
    if (widget.taskId != null) {
      ///校验
      Map<String, dynamic> queryParameters = Map();
      //任务类型 0 阅读 ； 1 学习；2 看视频
      queryParameters["taskFlag"] = 0;
      queryParameters["taskId"] = widget.taskId;
      //校验积分
      ResponseInfo checkResponsseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.taskConfigCheck,
        queryParameters: queryParameters,
      );
      if (checkResponsseInfo.success) {
        map["taskId"] = widget.taskId;
      } else {
        LogUtils.e("${checkResponsseInfo.message}");
      }
    }

    map["answerTime"] = currentTime;
    context.read<CountModel>().check();
    map["questionAnswers"] = context.read<CountModel>().commitList;

    _isFinish = false;
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance
        .postRequest(url: HttpHelper.submitAnswer, jsonMap: map);
    if (responseInfo.success) {
      ProblemEndModel problemEndModel =
          ProblemEndModel.fromJson(responseInfo.data);
      if (widget.topicEnum == TopicEnum.train ||
          widget.topicEnum == TopicEnum.pcExam) {
        //培训考试 关闭当前
        NavigatorUtils.pop(context, parameters: problemEndModel);
      } else {
        NavigatorUtils.openPageByFade(
            context,
            TopicEndPage(
              problemEndModel: problemEndModel,
              pageTitle: widget.themTitle ?? widget.pageTitle,
              categoryOne: widget.categoryOne,
              topicEnum: widget.topicEnum,
              categoryTwo: widget.categoryTwo,
            ),
            opaque: false,
            isReplace: true);
      }
    } else {
      ToastUtils.showToast("交卷失败 ${responseInfo.message}");
    }
  }

  buildLeftTime() {
    if (isCheckError) {
      return Container();
    }
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 4,
            ),
            Consumer<CountModel>(builder: (
              BuildContext context,
              CountModel contModel,
              Widget child,
            ) {
              return Text(
                "答对${contModel.rightCount}题",
                style: TextStyle(color: Colors.green),
              );
            }),
          ],
        ),
        SizedBox(
          width: 10,
        ),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 20,
            ),
            Consumer<CountModel>(builder: (
              BuildContext context,
              CountModel contModel,
              Widget child,
            ) {
              return Text(
                "答错${contModel.errorCount}题",
                style: TextStyle(color: Colors.red),
              );
            }),
          ],
        ),
      ],
    );
  }

  buildRightSubmit() {
    return TextButton(
      onLongPress: () {
        submitAn();
      },
      onPressed: () {},
      child: Text("交卷"),
    );
  }

  @override
  void dispose() {
    //3. 页面销毁时，移出监听者
    WidgetsBinding.instance?.removeObserver(this);
    if (_timer != null) {
      _timer.cancel();
    }
    _timeController.close();
    _pageStreamController.close();
    super.dispose();
  }

  Widget buildSubmitWidget() {
    if (widget.topicEnum == TopicEnum.error ||
        widget.topicEnum == TopicEnum.myError ||
        context.watch<CountModel>().problemList.length == 0 ||
        !_isFinish) {
      return null;
    }
    return FloatingActionButton.extended(
      icon: Icon(Icons.analytics),
      label: Text("交卷"),
      onPressed: () {
        submitAn();
      },
    );
  }

  Future<bool> _getExamDetails() async {
    ResponseInfo statisRresponseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.trainExamInfoUrl,
      encrypt: true,
      jsonMap: {"examId": widget.examBean.examId},
    );
    if (statisRresponseInfo.success) {
      BeanExamBean _beanExamBean =
          BeanExamBean.fromMap(statisRresponseInfo.data);
      if (_beanExamBean == null) {
        Get.defaultDialog(
            title: "提示",
            content: Text("暂无考试详情"),
            textCancel: "退出",
            onCancel: () {
              Get.back();
            });
        return false;
      }
      //考试时间
      int examTim = _beanExamBean.examTim;
      totalTime = examTim * 60;
      return true;
    } else {
      Get.defaultDialog(
          title: "提示",
          content: Text(statisRresponseInfo.message),
          textCancel: "退出",
          onCancel: () {
            Get.back();
          });
    }
    return false;
  }
}
